<template>
  <div class="content-box">
    <div class="content">
      <div class="content-item">
        <button class="button" @touchstart="startRecording" @touchend="stopRecording"
          :class="{ recording: isRecording }">
          {{ isRecording ? '松开结束' : '按住说话' }}

        </button>
        <div class="connecting display-none" id="connecting">建立连接中...</div>
        <span class="recognizing display-none" id="recognizing">识别中...</span>
      </div>
      <div class="content-item">
        <div id="recognizeText" class="recognize-content">{{ resultText }}</div>
      </div>
    </div>
  </div>
</template>

<script>
// zz.25-11.04.腾讯语音/实时语音 开始和结束方法说明，（开始结束中同步调用腾讯云和浏览器接口，所有监听代码都是监听浏览器）
export default {
  name: 'TencentSpeech',
  data() {
    return {
      params: {
        signCallback: signCallback, // 鉴权函数 用户提供鉴权函数，不传则为null
        appid: 1332379978,
        secretid: 'AKIDBG9oHYbPyJRM2ThhS1NXTJ1mLi2ECylQ',
        secretkey: 'WosiL4czA7sRmtoX4NSL0RecNvHQN6aq',
        // 实时识别接口参数
        engine_model_type: '16k_zh', // 引擎
        voice_format: 1,
        // 以下为非必填参数，可跟据业务自行修改
        hotword_id: '08003a00000000000000000000000000',
        needvad: 1,
        filter_dirty: 1,
        filter_modal: 1,
        filter_punc: 1,
        convert_num_mode: 1,
        word_info: 2
      },
      isRecording: false,
      pressTimer: null,
      recorder: null,
      speechRecognizer: null,
      isCanSendData: false,
      isCanStop: false,
      resultText: '',
    };
  },
  mounted() {

  },
  methods: {
    startRecording(e) {
      e.preventDefault();
      if (this.isRecording) return;

      this.pressTimer = setTimeout(() => {
        this.isRecording = true;
        // 防止默认事件（如文本选择）

        // 长按超过阈值，触发开始操作
        this.resultText = '';
        this.$('#connecting').show();
        this.speechRecognizer = null;
        this.isCanSendData = false;
        // 获取录音数据
        this.recorder = new WebRecorder();
        this.recorder.OnReceivedData = (res) => {
          // console.log(res) // res 为采集到浏览器数据s
          if (this.isCanSendData) {
            // 发送数据
            this.speechRecognizer.write(res);
          }
        };
        // 录音失败时
        this.recorder.OnError = (err) => {
          console.log(err);
          this.recorder.stop();
        };
        this.recorder.start();

        if (!this.speechRecognizer) {
          this.speechRecognizer = new SpeechRecognizer(this.params);
          console.log('创建实例', this.speechRecognizer);
        }

        // 开始识别
        this.speechRecognizer.OnRecognitionStart = (res) => {
          console.log('！！！开始识别', res);
          this.isCanSendData = true;
          this.isCanStop = true;
          this.$('#connecting').hide();
          this.$('#recognizing').show();
        };
        // 一句话开始
        this.speechRecognizer.OnSentenceBegin = (res) => {
          console.log('一句话开始', res);
        };
        // 识别变化时
        this.speechRecognizer.OnRecognitionResultChange = (res) => {
          console.log('识别变化时', res);
          // const currentText = `${this.resultText}${res.result.voice_text_str}`;
        };
        // 一句话结束
        this.speechRecognizer.OnSentenceEnd = (res) => {
          console.log('一句话结束', res);
          // this.resultText += res.result.voice_text_str;
        };
        // 识别结束
        this.speechRecognizer.OnRecognitionComplete = (res) => {
          console.log('！！！识别结束', res);
          this.isCanSendData = false;
        };
        // 识别错误
        this.speechRecognizer.OnError = (res) => {
          console.log('识别失败', res);
          this.isCanSendData = false;
          if (this.isCanStop) {
            this.speechRecognizer.stop();
          }
          this.recorder.stop();

          this.$('#connecting').addClass('display-none');
          this.$('#recognizing').addClass('display-none');
        };

        // 建立连接
        this.speechRecognizer.start();
      
      }, 200); // 200ms延迟确认长按
    },

    stopRecording(e) {
      if (!this.isRecording) {
        clearTimeout(this.pressTimer);
        return;
      }
      $('#recognizing').hide();
      this.recorder.stop();
      if (this.isCanStop) {
        this.speechRecognizer.stop();
      }
    },

    cleanupRecording() {
      // this.recorder = null;
      // this.speechRecognizer = null;
      // this.isCanSendData = false;
      // this.isCanStop = false;
      // if (this.pressTimer) {
      //   clearTimeout(this.pressTimer);
      // }
    },

  }
}
</script>

<style scoped>
/* 无需额外CSS，因为已通过public/index.html引入 */
.content-box .content {
  width: 100%;
  overflow: hidden;
  margin: 100px auto;
}

.content .content-item {
  width: 50%;
  float: left;
  text-align: center;
}

.left-content {
  width: 100%;
  height: 300px;
}

.connecting {
  color: #999;
  margin: 50px 0;
}

.recognizing {
  color: #999;
  margin: 0 10px;
}

.content .content-item .button {
  background: #187cff;
  border: 1px solid #478eea;
  color: #fff;
  text-align: center;
  border-radius: 3px;
  cursor: pointer;
  width: 160px;
  height: 40px;
  margin: 50px 0;
}

.button.end-btn {
  display: none;
}

.recognize-content {
  height: 200px;
  width: 360px;
  background-color: #eee;
  border: 1px solid #eee;
  border-radius: 5px;
  margin: auto;
  text-align: left;
  padding: 10px;
  box-sizing: border-box;
  overflow: scroll;
}

.display-none {
  display: none;
}
</style>